package com.example.excel.utils;

import java.util.List;

import androidx.annotation.IdRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;

public class NavigatorUtil {

    /**
     * 使用add+show+hide模式加载fragment
     * <p>
     * 默认显示位置[showPosition]的Fragment，最大Lifecycle为Lifecycle.State.RESUMED
     * 其他隐藏的Fragment，最大Lifecycle为Lifecycle.State.STARTED
     *
     * @param containerViewId 容器id
     * @param showPosition    fragments
     * @param fragmentManager FragmentManager
     * @param fragments       控制显示的Fragments
     */
    public static void loadFragmentsTransaction(
            @IdRes int containerViewId,
            FragmentManager fragmentManager,
            List<Fragment> fragments,
            int showPosition
    ) {
        if (!fragments.isEmpty()) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            for (int i = 0; i < fragments.size(); i++) {
                Fragment fragment = fragments.get(i);
                fragmentTransaction.add(containerViewId, fragment, fragment.getClass().getName());
                if (showPosition == i) {
                    fragmentTransaction.setMaxLifecycle(fragment, Lifecycle.State.RESUMED);
                } else {
                    fragmentTransaction.hide(fragment);
                    fragmentTransaction.setMaxLifecycle(fragment, Lifecycle.State.STARTED);
                }
            }
            fragmentTransaction.commit();
        } else {
            throw new IllegalStateException(
                    "fragments must not empty"
            );
        }
    }

    /**
     * 显示需要显示的Fragment[showFragment]，并设置其最大Lifecycle为Lifecycle.State.RESUMED。
     * 同时隐藏其他Fragment,并设置最大Lifecycle为Lifecycle.State.STARTED
     */
    public static void showHideFragmentTransaction(FragmentManager fragmentManager, Fragment showFragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.show(showFragment);
        transaction.setMaxLifecycle(showFragment, Lifecycle.State.RESUMED);
        //获取其中所有的fragment,其他的fragment进行隐藏
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != showFragment) {
                transaction.hide(fragment);
                transaction.setMaxLifecycle(fragment, Lifecycle.State.STARTED);
            }
        }
        transaction.commit();
    }
}
